 package session.stateless; 
 
import entity.PlainTextMessage;
import java.util.List;
import javax.ejb.Stateless; 
import javax.persistence.EntityManager; 
import javax.persistence.PersistenceContext; 
import javax.persistence.Query; 
 
@Stateless 
public class MessageMeSession implements MessageMeSessionLocal  
{ 
    @PersistenceContext 
    private EntityManager entityManager; 
     
     
     
    public List <PlainTextMessage> getAllPlainTextMessages(String receiver) 
    { 
        Query query = entityManager.createQuery("SELECT m FROM PlainTextMessage m WHERE m.receiver=:receiver"); 
        query.setParameter("receiver", receiver);
        return query.getResultList(); 
    } 
    
    public Long unreadCount()
    {
        Long count = new Long(0);
        Query query = entityManager.createQuery("SELECT m FROM PlainTextMessage m");
        
        List<PlainTextMessage> tempList = query.getResultList();
        
        for (PlainTextMessage p: tempList) {
            if (!p.getIsRead())
                count++;
        }
        return count;
    }
    
    public void deleteMessage(Long id)
    {
        PlainTextMessage message = entityManager.find(PlainTextMessage.class, id);
        System.out.println("Session delete");
        entityManager.remove(message);
        System.out.println("Session delete 2");
        entityManager.flush();
    }
} 